<?php

namespace App\Admin\Forms;

use App\Models\SwtGood;
use App\Models\SwtTyGood;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class AddToGoodsForm extends Form implements LazyRenderable
{
    use LazyWidget;
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $res = SwtGood::create($input);

        if($res) {
            return $this->response()->success('操作成功') ->refresh();
        } else {
            return $this->response()->error('操作失败');
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this -> hidden('bar_code');
        $this -> hidden('sku_id');

        $this -> row(function ($form) {
            $form -> width(4) -> display('bar_code');

            $form -> width(4) -> text('goods_name') -> rules('required|max:20')-> required();

            $form -> width(4) -> text('weight') -> rules('required|max:20')-> required();
        });

        $this -> row(function ($form) {
            $form -> width(4)
                -> currency('cost_price')
                -> symbol('¥')
                -> rules('required')
                -> required()
                -> saving(function ($value) {
                    return $value * 1000;
                });
            $form -> width(4)
                -> currency('sell_price')
                -> symbol('¥')
                -> rules('required|gte:cost_price')
                -> required()
                -> saving(function ($value) {
                    return $value * 100;
                });

            $form -> width(4) -> decimal('integral_num','积分');
        });

        $this -> row(function ($form) {
            $form -> width()->image('goods_picture','封面')->move('upload/goods/'.date('Ymd'))->uniqueName()->autoUpload();
        });
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        $id = $this->payload['id'];

        $info = SwtTyGood::firstWhere('id',$id);

        return [
            'bar_code'   => $info['bar_code'],
            'sku_id'     => $info['bar_code'],
            'goods_name' => $info['goods_name'],
            'weight'     => $info['weight']
        ];
    }
}
